<template>
  <!-- 发布的报价单 -->
  <div class="PriceSheet">
    <div class="body">
      <div class="g-con">
        <div class="main">
          <div class="title">{{ t('priceSheet.t1') }}</div>

          <div class="search flexsc">
            <div class="item">
              <el-input
                v-model="searchData.relationOrderNo"
                :placeholder="t('invitationQuotation.attr1_3')"
              />
            </div>
            <div class="item">
              <el-select-v2
                v-model="searchData.shipId"
                :options="shipOptions"
                :placeholder="t('invitationQuotation.p2')"
                clearable
                filterable
              />
            </div>
            <el-button
              type="primary"
              @click="handleSearch"
            >
              {{ t('invitationQuotation.b1') }}
            </el-button>
            <el-button
              type="primary"
              color="#252628"
              @click="handleReset"
            >
              {{ t('invitationQuotation.b2') }}
            </el-button>
          </div>
          <div class="g-order-list">
            <div
              class="li mt-2"
              v-for="item in listData"
              :key="item.id"
            >
              <div class="attr">
                <div class="item">
                  <span>{{ t('invitationQuotation.attr1_3') }}:</span>
                  <span>{{ item.orderNo }}</span>
                </div>
                <div class="item"></div>
                <div class="item">
                  <span>{{ t('invitationQuotation.attr3') }}:</span>
                  <span>{{ item.createByName }}</span>
                </div>
                <div class="item">
                  <span>{{ t('invitationQuotation.attr4') }}:</span>
                  <span>{{ dateFormat(item.createTime) }}</span>
                </div>

                <!-- 船舶信息 -->
                <template v-if="item.shippingId">
                  <div class="item">
                    <span>{{ t('shipping.l7') }}:</span>
                    <span>{{ item.shipowner }}</span>
                  </div>
                  <div class="item">
                    <span>{{ t('shipping.l3') }}:</span>
                    <span>{{ getDictLabel('ships_type', item.shippingType) }}</span>
                  </div>
                  <div class="item">
                    <span>{{ t('shipping.l8') }}:</span>
                    <span>{{ item.shipManagement }}</span>
                  </div>
                  <div class="item">
                    <span>{{ t('shipping.l12') }}:</span>
                    <span>{{ item.totalLength }}m</span>
                  </div>
                </template>
                <!-- 修船厂 -->
                <template v-else>
                  <div class="item">
                    <span>{{ t('invitationQuotation.attr10') }}:</span>
                    <span>{{ item.shipRepairYardName }}</span>
                  </div>
                  <div class="item">
                    <span>{{ t('invitationQuotation.attr11') }}:</span>
                    <span>{{ item.repairYardCountries }}</span>
                  </div>
                </template>

                <div class="item">
                  <span>{{ t('invitationQuotation.attr14') }}:</span>
                  <span>{{ item.detailCount || 0 }}{{ t('invitationQuotation.attr5_1') }}</span>
                </div>
                <div class="item">
                  <span>{{ t('invitationQuotation.attr15') }}:</span>
                  <span>{{ item.projectName }}</span>
                </div>
                <div class="item">
                  <span>{{ t('invitationQuotation.attr7') }}:</span>
                  <span>{{ dateFormat(item.quotationEndTime) }}</span>
                </div>
                <div class="item">
                  <span>{{ t('invitationQuotation.attr8') }}:</span>
                  <span>{{ item.quotaManagerPerson }}</span>
                </div>
                <div class="item">
                  <span>{{ t('invitationQuotation.attr9') }}:</span>
                  <span>{{ getDictLabel('quotation_status', item.status) }}</span>
                </div>
              </div>

              <div class="bottom flexsb mt-3">
                <div class="">
                  <el-button
                    type="primary"
                    @click="open(item)"
                  >
                    {{ t('priceSheet.b1') }}
                  </el-button>
                  <el-button
                    v-if="isEdit(item) && isQuotaCreateBy(item) && item.canEditerQuota"
                    type="primary"
                    @click="handleEdit(item)"
                  >
                    {{ t('priceSheet.b2') }}
                  </el-button>
                  <el-button
                    v-if="isEdit(item) && isAdmin && item.status === '3' && item.canEditerQuota"
                    type="primary"
                    @click="hanldleSubmit(item)"
                  >
                    {{ t('priceSheet.b3') }}
                  </el-button>
                  <template v-if="item.status === '1' && isAdmin">
                    <!-- status	0已拒绝，1中标未确认，2中标已确认，3未提交，4未中标 -->
                    <el-button
                      type="primary"
                      @click="handleAcceptBid(item)"
                    >
                      {{ t('priceSheet.b4') }}
                    </el-button>
                    <el-button
                      type="primary"
                      @click="handleRejectBid(item)"
                    >
                      {{ t('priceSheet.b5') }}
                    </el-button>
                  </template>
                </div>
              </div>
            </div>
          </div>

          <div class="flexcc mt-3">
            <el-pagination
              layout="prev, pager, next"
              :hide-on-single-page="total <= page.pageSize"
              :total="total"
              v-model:current-page="page.pageNum"
              :page-size="page.pageSize"
              @current-change="handleCurrentChange"
            >
            </el-pagination>
          </div>
        </div>
      </div>
    </div>

    <!-- 接受中标 -->
    <AcceptBid
      v-if="dialogAcceptBid"
      :visible="dialogAcceptBid"
      :quotationId="editId"
      type="3"
      @close="dialogAcceptBid = fasle"
      @getList="getList"
    />

    <!-- 拒绝中标 -->
    <RejectBid
      v-if="dialogRejectBid"
      :visible="dialogRejectBid"
      :objId="editId"
      type="3"
      @close="dialogRejectBid = fasle"
      @getList="getList"
    />

    <!-- 提交确认 -->
    <Confirm
      v-if="submitConfirmDialog"
      :visible="submitConfirmDialog"
      :text="t('DockOrderOnlineQuotation.c1')"
      @close="submitConfirmDialog = false"
      @cancel="submitConfirmDialog = false"
      @confirm="submitConfirmFn"
    />

    <!-- 设置访问密码 -->
    <AccessPassword
      v-if="dialogAccessPassword"
      :visible="dialogAccessPassword"
      @close="dialogAccessPassword = false"
      @setAccessPassword="setAccessPassword"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onBeforeMount, watch, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { selectShcwQuotationAssistOrderListApi, submitInListApi, getQuotaOrderShipApi, inviteEditingApi, saveQuotationApi } from '@/service/externalAssistance'
import { shippingListByEnterpriseIdApi } from '@/service/shipping'
import { useI18n } from 'vue-i18n'
const { t, locale } = useI18n()
import { dateFormat, openUrl } from '@/utils/index'
import moment from 'moment'
import useLogin from '@/stores/login'

import AcceptBid from '../AcceptBid.vue'
import RejectBid from '../RejectBid.vue'
import Confirm from '@/components/Confirm.vue'
import AccessPassword from '@/views/userCenter/AccessPassword.vue'

import useDict from '@/hooks/useDict'
const { dictData, getDictData, getDictLabel } = useDict()

const router = useRouter()
const route = useRoute()
const storeLogin = useLogin()

watch(locale, () => {
  init()
})

onBeforeMount(() => {
  init()
})

// 查询
const searchData = ref({})
const shipOptions = ref([])
const getShippingList = () => {
  getQuotaOrderShipApi().then(({ data }) => {
    shipOptions.value = data.map((r) => {
      return {
        value: r.id,
        label: r.shippingName
      }
    })
  })
}
const handleSearch = () => {
  page.value.pageNum = 1
  if (searchData.value.shipId) {
    searchData.value.shipList = [searchData.value.shipId]
  }
  getList()
}
const handleReset = () => {
  page.value.pageNum = 1
  searchData.value = {}
  getList()
}

// 报价单列表
const listData = ref([])
const page = ref({
  pageNum: 1, // 当前页码
  pageSize: 6 // 每页条数
})
const total = ref(0) // 总数
const getList = () => {
  selectShcwQuotationAssistOrderListApi(page.value, searchData.value).then(({ data: rows, total: t }) => {
    listData.value = rows
    total.value = t
  })
}
// 分页
const handleCurrentChange = (val) => {
  getList()
}

// 查看
const open = (item) => {
  openUrl('/user/externalAssistance/onlineQuotation', { id: item.id })
}

// 编辑
const handleEdit = async (item) => {
  let id = item.id

  // 待开标状态
  if (item.status === '4') {
    // 创建新版本
    await inviteEditingApi({
      oldId: id
    }).then(({ data }) => {
      id = data
      getList()
    })
  }

  openUrl('/user/externalAssistance/onlineQuotation', {
    id,
    quotaCreateBy: item.quotaCreateBy
  })
}

// 是否可以编辑/提交报价
const isEdit = (item) => {
  // versionNumber 为0报价截至时间到期后不允许编辑，不为0根据状态处理
  //return item.versionNumber == 0 ? Number(moment().format('X')) < Number(item.quotationEndTime) && !['0', '1', '2'].includes(item.status) : !['0', '1', '2'].includes(item.status)
  if (item.versionNumber == 0){
    if (!['0', '1', '2'].includes(item.status)){
      return true
    }else if ( Number(moment().format('X')) < Number(item.quotationEndTime) && !['0', '1', '2'].includes(item.status) ){
      return true
    }
  }else{
    if (!['0', '1', '2'].includes(item.status)){
      return true
    }
  }
  return false
}

// 正在操作的id
const editId = ref(null)

// 访问密码 弹窗
const dialogAccessPassword = ref(false)
// 设置访问密码
const setAccessPassword = (val) => {
  saveQuotationApi({
    accessPassword: val,
    id: editId.value
  }).then(({ msg }) => {
    ElMessage.success(msg)
    submitConfirmDialog.value = true
  })
}

// 提交报价单
const submitConfirmDialog = ref(false)
const hanldleSubmit = ({ accessPassword, id }) => {
  editId.value = id
  // 如果未设置密码
  if (!accessPassword) {
    dialogAccessPassword.value = true
    return
  }
  submitConfirmDialog.value = true
}
const submitConfirmFn = () => {
  submitInListApi({
    quotationId: editId.value
  }).then(({ msg }) => {
    ElMessage.success(msg)
    submitConfirmDialog.value = false
    getList()
  })
}

// 接受中标
const dialogAcceptBid = ref(false)
const handleAcceptBid = (item) => {
  dialogAcceptBid.value = true
  editId.value = item.id
}

// 拒绝中标
const dialogRejectBid = ref(false)
const handleRejectBid = (item) => {
  dialogRejectBid.value = true
  editId.value = item.id
}

// 是否是管理员
const isAdmin = computed(() => {
  return storeLogin?.userInfo?.isAdmin === '1'
})

// 是否是报价员
const isQuotaCreateBy = (item) => {
  return storeLogin?.userInfo?.id === item.quotaCreateBy
}

//
const init = async () => {
  getShippingList()
  await getDictData('quotation_status')
  await getDictData('ships_type')
  getList()
}
</script>

<style scoped lang="scss">
.PriceSheet {
  .el-button {
    min-width: 140px;
  }
  .body {
    padding: 30px 0 70px;
    background: #f5f5f5;
    margin-bottom: -76px;

    .main {
      background: #fff;
      padding: 25px 35px;
      .title {
        border-bottom: 2px solid #212121;
        padding-bottom: 20px;
        text-transform: uppercase;
        font-weight: bold;
        font-size: 20px;
        color: var(--mainColor);
      }
      .search {
        margin-top: 25px;
        .item {
          width: 200px;
          margin-right: 20px;
        }
      }
    }
  }
}
</style>
